<?php

abstract class dbtables_handler {

    private $host;        // mySQL host to connect to
    private $username;        // mySQL username
    private $password;      // mySQL password
    private $database;      // mySQL database to select
    private $connection;     //the database connection link identifier
    private $autoSlashes;        // the class will add/strip slashes when it can
    public $lastError;      // holds the last error. Usually mysql_error()
    protected $lastQuery;      // holds the last query executed.
    protected $lastInsertID;    // holds the last insert id.
    protected $rowCount;      // holds the last number of rows from a select
    protected $tableName;
    protected $childTableName;

    private function initializeDataBase() {
        //My machine with IP Address 146.141.77.56
        $this->username = "root";
        $this->password = "password.1";
        $this->host = "localhost";
        $this->database = "CGECarbon";
        $this->autoSlashes = true;
        /* $this->username = "bpiadmin";
          $this->password = "as@#77bh";
          $this->host = "localhost";
          $this->database = "bpi";
          $this->autoSlashes = true; */
    }

    /* Opens a connection to MySQL and selects the database. */
    protected function connectToDB()
    {
                $this->initializeDataBase();
// try to establish the connection.
                 if (!$this->connection) {
        $this->connection = mysql_pconnect($this->host, $this->username, $this->password);
                 }
//        print_r($this->connection);
    }
    protected function openDB() {

        // check for error in establishing a connection
        if (!$this->connection) {
            $this->lastError = mysql_error();
            return false;
        }
        // Select the database and check for error in selecting database
        if (!mysql_select_db($this->database,  $this->connection)) {
            $this->lastError = mysql_error();
            return false;
        }
        return $this->connection;  // connected
    }

    protected function checkIfObjectisPlacable($base_tile_table, $x_pos, $y_pos, $z_pos) {
        if (mysql_num_rows(mysql_query("SELECT * FROM $base_tile_table WHERE x_pos = '$x_pos' AND y_pos = '$y_pos' AND z_pos = '$z_pos'"))) {
            return true;
        }
    }

    protected function checkIfCoordinatesExist($x_pos, $y_pos, $z_pos) {
        if (mysql_num_rows(mysql_query("SELECT * FROM $this->tableName WHERE x_pos = '$x_pos' AND y_pos = '$y_pos' AND z_pos = '$z_pos'"))) {
            return true;
        } else {
            return false;
        }
    }

    protected function getIDOfTile($x_pos, $y_pos, $z_pos) {
        $resultArray = array();

        $result = mysql_query("SELECT * FROM $this->tableName WHERE x_pos = '$x_pos' AND y_pos = '$y_pos' AND z_pos = '$z_pos'") or die(mysql_error());
        return $this->getAssocArray($result);
        while ($row = mysql_fetch_array($result)) {
            $resultArray['id'][] = $row['id'];
        }
        return $resultArray;
    }

    protected function getAllStagnantGameObjects($level) {
        $result = mysql_query("SELECT * FROM $this->tableName
                    WHERE level = '$level'
order by z_pos, x_pos, y_pos, state_number asc") or die(mysql_error());
        return $this->getSpecialGameObjectArray($result);
    }

    protected function getSpecialGameObjectArray($result) {
        $resultArr = array();
        $childArray = array();
        $z = -1;
        while ($row = mysql_fetch_assoc($result)) {

            if ($z != $row['z_pos']) {
                //    $childArray[$row['z_pos']] ;
//                   =  array("x"=>"$row[x_pos]","y"=>"$row[y_pos]","h"=>"$row[virtual_h]");
                $z = $row['z_pos'];
                $childArray['z' . $z] = array();
            }
//          else
//          {
//
//
//          }
           // $path = htmlentities($row[image_path], ENT_QUOTES);
            //     $path = $row[image_path];
            array_push($childArray['z' . $z], array("metadata_name" => "$row[object_metadataname]", "x" => "$row[x_pos]", "y" => "$row[y_pos]", "h" => "$row[virtual_h]", "path" => "$row[image_path]", "object_width" => "$row[object_width]", "object_length" => "$row[object_length]", "object_is_virtual" => "$row[object_is_virtual]", "number_of_states" => "$row[number_of_states]", "state_number" => "$row[state_number]", "animatable" => "$row[animatable]", "number_of_slides" => "$row[number_of_animatable_states]", "animation_speed" => "$row[animation_speed]", "animate_once" => "$row[animate_once]", "animation_height" => "$row[animation_height]", "object_state" => "$row[state_type]"));
        }
        return $childArray;
    }

    protected function getSelectedTiles($xmin, $xmax, $ymin, $ymax) {
        $result = mysql_query("SELECT * FROM $this->tableName WHERE x_pos >= '$xmin' AND x_pos <= '$xmax' AND y_pos >= '$ymin' AND y_pos <= '$ymax'
         order by z_pos, x_pos, y_pos asc") or die(mysql_error());
        return $this->getSpecialArray($result);
    }

    protected function getAllTiles($mapID) {
//   $result = mysql_query("SELECT * FROM $this->tableName
//            group by z_pos
//            order by x_pos, y_pos asc") or die(mysql_error());
        $result = mysql_query("SELECT * FROM $this->tableName
              WHERE mapid = 1
order by z_pos, x_pos, y_pos asc") or die(mysql_error());
        return $this->getSpecialArray($result);
    }

    protected function getAnimatableTiles($xmin, $xmax, $ymin, $ymax, $mapID) {
        $result = mysql_query("SELECT * FROM $this->tableName
WHERE animatable = true AND x_pos >= '$xmin' AND x_pos <= '$xmax' AND y_pos >= '$ymin' AND y_pos <= '$ymax'
order by z_pos, x_pos, y_pos asc ") or die(mysql_error());
        return $this->getSpecialArray($result);
    }

    protected function getAllPlainTiles() {
        $result = mysql_query("SELECT * FROM $this->tableName
WHERE animatable = false
order by z_pos, x_pos, y_pos asc ") or die(mysql_error());
        return $this->getSpecialArray($result);
    }

    private function getSpecialArray($result) {

        $resultArr = array();
        $childArray = array();
        $z = -1;
        while ($row = mysql_fetch_assoc($result)) {

            if ($z != $row['z_pos']) {

                $z = $row['z_pos'];
                $childArray['z' . $z] = array();
            }

//           $path = htmlentities($row[image_path], ENT_QUOTES);
          //  $path = $row['image_path'];
            //$path =$row[image_path];
            array_push($childArray['z' . $z], array("metadata_name" => "$row[metadata_name]", "x" => "$row[x_pos]", "y" => "$row[y_pos]", "h" => "$row[virtual_h]", "path" => "$row[image_path]", "animatable" => "$row[animatable]", "number_of_slides" => "$row[number_of_slides]", "animation_speed" => "$row[animation_speed]", "loop_once" => "$row[loop_once]"));
        }
        return $childArray;
    }


    protected function getAllRows()
    {
              $result = mysql_query("SELECT * FROM $this->tableName") or die(mysql_error());
        return $this->getAssocArray($result);
    }

    private function getTilePropertyArray($result)
    {
        $lastID = -1;
        $tempArr = array();
        while ($row = mysql_fetch_assoc($result))
        {
            $tempArr[$row['id']]['x_pos'] = $row['x_pos'];
            $tempArr[$row['id']]['y_pos'] = $row['y_pos'];
            $tempArr[$row['id']]['z_pos'] = $row['z_pos'];
            $tempArr[$row['id']]['virtual_h'] = $row['virtual_h'];
            $tempArr[$row['id']]['metadata_name'] = $row['metadata_name'];
            $tempArr[$row['id']][$row['name']] = $row['propertyvalue'];
        }
        return $tempArr;
    }
    protected function getAllTileProperties($mapID)
    {
                     $result = mysql_query("SELECT a.id, a.metadata_name, a.x_pos,a.y_pos,a.z_pos,a.virtual_h,c.name,b.propertyvalue
                         FROM tbl_stagnant_tiles a,tbl_stagnant_tile_properties b, tbl_stagnant_tile_properties_pool c
                         WHERE b.propertykey = c.id AND a.id = b.tileid AND a.mapid= $mapID") or die(mysql_error());
//                             $result = mysql_query("SELECT *
//                         FROM tbl_stagnant_tiles
//                         WHERE mapid= $mapID") or die(mysql_error());
        return $this->getTilePropertyArray($result);


    }

    protected function getAllStaticObjectStatuses()
    {
     
    }

       protected function deleteEntireMap($mapID) {
        mysql_query("DELETE FROM $this->tableName WHERE mapid=$mapID")
                or die(mysql_error());
    }

    protected function deleteData($id) {
        mysql_query("DELETE FROM $this->tableName WHERE id=$id")
                or die(mysql_error());
    }

    protected function emptyTable() {
        mysql_query("DELETE FROM $this->tableName WHERE 1")
                or die(mysql_error());
    }

    protected function insertProperty($dataStringCommaSeperated) {
        if (!($this->openDB())) {
            return $this->lastError;
        }

        $query = "SELECT  MAX(id) FROM $this->childTableName";
        $result = mysql_query($query);
        $maxID = mysql_fetch_array($result);
        if ($maxID[0] == null) {
            $nextID = 1;
        } else {
            $nextID = $maxID[0]+=1;
        }
//$nextID = $maxID[0]+=1;
        $data = "'$nextID',$dataStringCommaSeperated";
        if (mysql_query("insert into $this->childTableName values(" . $data . ")")) {
            return $nextID;
        } else {
            return false;
        }
    }

    /* Insert data values into the appropriate Table in the database. $values is either 1 value String or an Array of values */

        protected function getAssocArray($result) {
        $resultArray = array();
        while ($row = mysql_fetch_assoc($result)) {
            $resultArray[] = $row;
        }
        return $resultArray;
    }
    
    protected function querySingleEntry($id)
    {
          $result = mysql_query("SELECT * FROM $this->tableName WHERE id >= '$id'") or die(mysql_error());
        return $this->getAssocArray($result);
    }

    protected function insertNewStaticGameObject($dataStringCommaSeperated)
    {
            if (!($this->openDB())) {
            return $this->lastError;
        }
            $query = "SELECT  MAX(id) FROM $this->tableName";
        $result = mysql_query($query);
        $maxID = mysql_fetch_array($result);
        if ($maxID[0] == null) {
            $nextID = 1;
        } else {
            $nextID = $maxID[0]+=1;
        }
        
                    $query = "SELECT  MAX(object_id) FROM $this->tableName";
        $result = mysql_query($query);
        $maxObjectID = mysql_fetch_array($result);
        if ($maxObjectID == null) {
            $nextObjectID = 1;
        } else {
            $nextObjectID = $maxObjectID[0]+=1;
        }

        $data = "'$nextID',$dataStringCommaSeperated,'$nextObjectID'";
        if (mysql_query("insert into $this->tableName values(" . $data . ")")) {
            return $nextObjectID;
        } else {
            return false;
        }

    }
    protected function insertData($dataStringCommaSeperated) {
        //  return "dsdffsdfsdfsd";
    
        if (!($this->openDB())) {
            return $this->lastError;
        }

        $query = "SELECT  MAX(id) FROM $this->tableName";
        $result = mysql_query($query);
        $maxID = mysql_fetch_array($result);
        if ($maxID[0] == null) {
            $nextID = 1;
        } else {
            $nextID = $maxID[0]+=1;
        }


        $data = "'$nextID',$dataStringCommaSeperated";
        if (mysql_query("insert into $this->tableName values(" . $data . ")")) {
            return $nextID;
        } else {
            return false;
        }
    }

    // abstract public function insertSingleEntry($metadata_name, $image_path,$image_type,$x_pos,$y_pos,$z_pos,$virtual_h,$animatable,$number_of_animation_slides,$animation_speed);
    abstract public function deleteSingleEntry($id);

    abstract public function getAllEntries($mapID);

    abstract public function deleteAllEntries();

    abstract public function getSingleEntry($id);
}

?>
